<template>
  <div class="main-box">
    <div class="mocks-record-main">
      <audio :src="audioSrc" ref="audio" @ended="_stopPlayVideo"></audio>
      <div class="record-des" v-html="questionTitle"></div>
      <!--录音部分-->
      <div class="spoken-main">
        <!--准备时间-->
        <div class="spoken-step" v-show="currentState === 'ready'">
          <div class="step-msg-bar">
            <span class="step-msg">Preparation Time</span>
          </div>
          <div class="step-timer-bar">
            <span class="step-timer" v-html="showTimeFormat(readingTime)"></span>
          </div>
        </div>
        <!--录音时间-->
        <div class="spoken-step" v-show="currentState === 'recording'">
          <div class="step-msg-bar">
            <span class="step-msg">Record Time</span>
          </div>
          <div class="step-timer-bar">
            <span class="step-timer" v-html="showTimeFormat(recordTime)"></span>
          </div>
          <div class="step-icon-bar">
            <span class="mocks-icon icon-recording">录音中</span>
          </div>
        </div>
        <!--录音完毕-->
        <div class="spoken-step step-over" v-show="currentState === 'over'">
          <div class="step-msg-bar">
            <span class="step-msg">Record Time</span>
          </div>
          <div class="step-timer-bar">
            <span class="step-timer"><i>00</i><i>00</i></span>
          </div>
          <div class="step-tips" v-show="endState === 'upload'">上传录音中 <span class="state-dot"><em></em><em></em><em></em><em></em><em></em></span></div>
          <div class="step-tips" v-show="endState === 'end'">答题完毕，请点击右上角按钮进行下一步</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex';
  import MP3Recorder from '../utils/mp3Recorder';
  import '../utils/qiniu';
  function getFileName () {
    let d = new Date();
    let t = d.getFullYear() + ''
      + ((d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1)) + ''
      + ((d.getDate()) < 10 ? '0' + (d.getDate()) : (d.getDate())) +  ''
      + d.getHours() + ''
      + ((d.getMinutes()) < 10 ? '0' + (d.getMinutes()) : (d.getMinutes()));

    let k = 'xxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = Math.random() * 16 | 0;
      let v = c === 'x' ? r : ((r & 0x3) | 0x8);
      return v.toString(16);
    });
    return t + k;
  }
  export default {
    name: "MocksSpeakQuestion",
    componentName: 'MocksSpeakQuestion',
    data () {
      return {
        currentState: 'ready', //播放状态
        endState: 'upload',
        questionTitle: '', //题目标题
        questionId: '',
        audioSrc: '', //题目录音
        readingTime: 0, //准备时间
        recordTime: 0, //录音时间
        readInv: null,
        recordInv: null,
        mp3Blob: null,
        isRecording: false, //是否在录音
        isUploadOver: true //是否上传成功
      };
    },
    // created () {
    //   //创建完毕调用
    //   //更新小题序号
    //   let questionNum = this.$route.params.questionNum;
    //   this.updateQuestionNum(parseInt(questionNum));
    // },
    mounted () {
      if (!this.isAllowRecord) {
        let mp3Recorder = new MP3Recorder({
          CancelCallback: this.CancelCallback,
          SuccessCallback: this.SuccessCallback
        });
        this.updateMp3Recorder(mp3Recorder);
      }
      if (this.partInfo) {
        this._initBaseInfo();
      }
    },
    //销毁
    destroyed () {
      if (this.isRecording) {
        this.isRecording = false;
        if (this.mp3Recorder) {
          this.mp3Recorder.stop()
        }
      }
    },
    beforeRouteEnter (to, from, next) {
      next(vm => {
        let currentPart = vm.$route.params.currentPart;
        vm.updateCurrentPart(currentPart);
      });
    },
    // watch ??
    watch: {
      'partInfo' (partInfo) {
        if (partInfo && partInfo.question_list && partInfo.question_list.length) {
          let questionList = this.partInfo.question_list;
          this._initBaseInfo();
        }
      },
      '$route.params.questionNum' (val) {
        if (this.partInfo) {
          this._initBaseInfo();
        }
      }
    },
    computed: {
      ...mapState([
        'paperInfo',
        'paperId',
        'courseId',
        'currentPart',
        'partInfo',
        'paperType',
        'totalPart',
        'isAllowRecord',
        'mp3Recorder',
        'questionNum'
      ]),
    },
    methods: {
      ...mapActions([
        'updateCurrentPart',
        'updateDisabledPrevBtn',
        'updateDisabledNextBtn',
        'updateShowHeaderPart',
        'updateIsAllowReocrd',
        'updateMp3Recorder',
        'updateQuestionNum',
      ]),
      _initBaseInfo () {
        this.updateDisabledNextBtn(true);
        this.updateDisabledPrevBtn(true);
        let questionNum = this.$route.params.questionNum;
        this.updateQuestionNum(parseInt(questionNum));
        let questionList = this.partInfo.question_list;
        let readingTime = questionList[this.questionNum - 1].reading_time;
        let recordTime = questionList[this.questionNum - 1].record_time;
        if (readingTime) {
          this.readingTime = parseInt(readingTime);
        }
        if (recordTime) {
          this.recordTime = parseInt(recordTime);
        }
        this.currentState = 'ready';
        this.endState = 'upload';
        this.audioSrc = questionList[this.questionNum - 1].audio_url;
        this.$nextTick(() => {
          let $audio = this.$refs['audio'];
          if ($audio  && this.audioSrc) {
            this._startPlayVideo();
          }
        });
        this.questionId = questionList[this.questionNum - 1].id;
        let str = questionList[this.questionNum - 1].question;
        this.questionTitle = (str && typeof str === 'string') ? str.replace(/\n/g, '<br />').replace(/\t/g, '&nbsp;') : '';
      },
      //准备计时录音
      _startReadyInv () {
        this.readInv = setInterval(() => {
          if (this.readingTime > 0) {
            this.readingTime--;
          } else {
            clearInterval(this.readInv);
            this.currentState = 'recording';
            this._startRecordInv();
          }
        },1000)
      },
      // 开始播放录音
      _startPlayVideo () {
        let $audio = this.$refs['audio'];
        $audio.play();
      },
      // 播放完毕进行录音
      _stopPlayVideo () {
        // let $audio = this.$refs['audio'];
        // $audio.pause();
        if (this.isAllowRecord) {
          this._startReadyInv();
        }
      },
      // 开始进行录音
      _startRecordInv () {
        this.isRecording = true;
        if (this.isAllowRecord) {
          if (this.mp3Recorder) {
            this.mp3Recorder.start();
            this.recordInv = setInterval(() => {
              //TODO: 递减时间完成后调用stop函数
              if (this.recordTime > 0) {
                this.recordTime--;
              } else {
                clearInterval(this.recordInv);
                this.currentState = 'over';
                this._stopRecord();
              }
            }, 1000);
          }
        }else{
          layer.alert("无法打开麦克风", {title: false});
        }
      },
      _stopRecord() {
        this.isRecording = false;
        if (this.mp3Recorder) {
          this.mp3Recorder.stop()
        }
        this.mp3Recorder.getMp3Blob(blob => {
          this._doUpload(blob);
        });
      },
      _doUpload (blob) {
        // TODO:进行上传所录制的音频
        let _this = this;
        $.ajax({
          url: "http://service.wowtalk.com/Upfile/getTokenByQiniu",
          type:'post',
          data: {
            bucket: 'video',
            domain: "http://e.wowtalk.com/",
            random_string: (typeof random_string == 'string' ? random_string : ''),
            secret_string: (typeof secret_string == 'string' ? secret_string : '')
          },
          dataType: 'json',
          success: function(res){
            let token = res.uptoken;
            let domain = res.domain;
            let config = {
              useCdnDomain: true,
              disableStatisticsReport: false
            };
            let putExtra = {
              fname: getFileName() + '.mp3',
              params: {},
              mimeType: null
            };
            _this.uploadWithSDK(blob, token, putExtra, config, domain);
          },
          error: function () {
            layer.msg('获取token失败');
          }
        })
      },
      _doSubmitAnswer (name, domain) {
        let _this = this;
        $.ajax({
          // url: '/api/mocks/submit/speak',
          url: 'http://www.ruixinnj.com/test/save_video_url',
          data: {
            paperId: this.paperId,
            questionId: this.questionId,
            audioName: name,
            domain: domain,
            random_string: (typeof random_string == 'string' ? random_string : ''),
            secret_string: (typeof secret_string == 'string' ? secret_string : '')
          },
          type: 'post',
          dataType: 'json',
          success: function (response) {
            if (response.status == 1) {
              _this.isUploadOver = true;
              _this.endState = 'end';
              _this.updateDisabledNextBtn(false);
            }else{
              layer.msg(response.msg)
            }
          }
        })
      },
      submitPaper () {
        let _this = this;
        $.ajax({
          url: 'http://www.ruixinnj.com/report/set_status',
          // url: '/api/mocks/result',
          type: 'post',
          dataType: 'json',
          data: {
            paperId: this.paperId,
            courseId: this.courseId,
            paperType: this.paperType,
            random_string: (typeof random_string == 'string' ? random_string : ''),
            secret_string: (typeof secret_string == 'string' ? secret_string : '')
          },
          success: function (response) {
            if (response.status == 1) {
              let _data = response.data;
              _this.updateShowHeaderPart(false);
              // _this.$router.replace(`/result/${_this.paperId}/1/0`)
              _this.$router.replace(`/result/${_this.paperId}/${_data.result}/${_data.score}`)
            } else {
              layer.msg(response.msg);
            }
          }
        })
      },
      uploadWithSDK (file, token, putExtra, config, domain) {
        let _this = this;
        let observable;
        let key = encodeURIComponent(getFileName() + '.mp3');

        // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
        let error = function(err) {
          layer.msg(err);
          _this.isUploadOver = false;
        };
        let complete = function(res) {
          _this._doSubmitAnswer(res.key, domain);
        };
        let next = function(response) {
        };
        let subObject = {
          next: next,
          error: error,
          complete: complete
        };
        let subscription;
        // 调用sdk上传接口获得相应的observable，控制上传和暂停
        observable = qiniu.upload(file, key, token, putExtra, config);
        subscription = observable.subscribe(subObject);
      },
      showTimeFormat (time) {
        let min = Math.floor(time / 60);
        let sec = Math.floor(time % 60);
        let minStr = min > 9 ? '' + min : '0' + min;
        let secStr = sec > 9 ? '' + sec : '0' + sec;
        return `<i>${minStr}</i><i>${secStr}</i>`;
      },
      CancelCallback (msg) {
        layer.alert('请点击允许使用麦克风', {title: false});
        this.updateIsAllowReocrd(false);
      },
      SuccessCallback () {
        this.updateIsAllowReocrd(true);
        // this._startPlayVideo();
        // this._startReadyInv();
      },
      submitAnswer (callback) {
        if (!this.isUploadOver) return;

        let question_list = this.partInfo.question_list;
        //当前part等于总part 当前题为最后一题
        if (this.currentPart == this.totalPart && this.questionNum == question_list.length) {
          layer.confirm('<img src="/paper/images/dialog_bg.png" alt="">' +
            '<p>确认要提交试卷吗？</p>', {title: false}, (index) => {
            // TODO: 进行提交试卷
            this.submitPaper();
            layer.close(index);
          });
        } else {
          if (this.questionNum >= question_list.length) {
            callback();
          } else {
            let questionNum = this.questionNum;
            questionNum++;
            let _path = `/speak/${this.paperId}/${this.courseId}/${this.currentPart}/${questionNum}`;
            this.$router.push(_path);
          }
        }
      }
    }
  }
</script>
